package com.xjnt.frameworks.plugin.sql.criterion.expression;

import java.util.List;

import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.xjnt.frameworks.plugin.sql.consts.KeyWord;
import com.xjnt.frameworks.plugin.sql.criterion.Criterion;
import com.xjnt.frameworks.plugin.sql.criterion.SqlCriteria;
import com.xjnt.frameworks.plugin.sql.criterion.SqlType;
import com.xjnt.frameworks.plugin.sql.criterion.TypedValue;

public class InExpression implements Criterion {

	private static final long serialVersionUID = 1L;

	private String columnName;
	private Object[] values;

	public InExpression(String columnName, Object[] values) {
		this.columnName = columnName;
		this.values = values;
	}

	@Override
	public String toSql(SqlCriteria criteria) {
		StringBuilder sql = new StringBuilder();
		if (criteria.isExists(columnName)) {
			int len = values.length;
			if (len > 0) {
				sql.append(columnName);
				if (len > 1) {
					sql.append(" ");
					sql.append(KeyWord.IN.getValue());
					sql.append("(");
					for (int i = 0; i < len; i++) {
						if (i < len - 1) {
							sql.append("?, ");
						} else {
							sql.append("?");
						}
					}
					sql.append(")");
				} else {
					sql.append(KeyWord.EQ.getValue()).append("?");
				}
				return sql.toString();
			} else {
				throw new ActiveRecordException("The inExpression values cannot be null ");
			}
		} else {
			throw new ActiveRecordException("The " + columnName + " is not exists ");
		}
	}

	@Override
	public TypedValue[] getTypedValues(SqlCriteria criterion) {
		List<TypedValue> lstTypedValue = Lists.newArrayList();
		for (Object value : values) {
			lstTypedValue.add(new SqlType().getTypedValue(criterion, columnName, value));
		}
		return lstTypedValue.toArray(new TypedValue[lstTypedValue.size()]);
	}

	public String getColumnName() {
		return columnName;
	}

	public Object[] getValues() {
		return values;
	}

}
